<template>
  <div>
    <h3>个人资料</h3>
<!--    头像更换Dialog-->
    <el-dialog
      title="更换头像"
      :visible.sync="isShowChangePhotoDialogVisible"
      :close-on-click-modal="false"
    >

      <div class="upload_part">
       <el-upload
         action="#"
         ref="upload"
         :http-request=" uploadHeadPortrait"
         :before-upload="checkFile"
         :show-file-list="false"
         :file-list="fileList"
         :disabled="buttonDisabled"
       >
         <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="头像">
         <i v-else class="el-icon-plus avatar-uploader-icon"></i>
       </el-upload>
        </div>
      <p style="font-size:12px;padding: 5px;">
        请选择图片上传：大小180 * 180像素支持JPG、PNG等格式，图片需小于2M</p>
      <div slot="footer"  >
        <el-button type="primary"
                   id="submit"
                   @click="submitAvatar(imageUrl)"
                   :disabled="buttonDisabled"
        > 保存</el-button>
        <el-button @click="isShowChangePhotoDialogVisible= false" :disabled="buttonDisabled">取消</el-button>
      </div>
    </el-dialog>

<!--    修改用户基本信息Dialog-->
    <el-dialog
      :visible.sync="isShowChangeInfDialogVisible"
      title="编辑信息"
      :close-on-click-modal="false"
    >
      <CommonForm
        :form="newUserInfForm"
        :formLabel="newUserInfFormLabel"
        :formConfig="newUserInfFormConfig"
      >
      </CommonForm>
      <el-button size="small"
                 style="width: 90px;position:absolute;top: 335px;left:260px;"
                 @click="getCode"
                 :disabled="getCodeBtnDisable" >
        {{timeCounter||"获取验证码"}}</el-button>
      <div slot="footer">
        <el-button type="primary" @click="saveUserInf(newUserInfForm)" :disabled="buttonDisabled" >保存</el-button>
        <el-button @click="isShowChangeInfDialogVisible = false" :disabled="buttonDisabled">取消</el-button>
      </div>
    </el-dialog>
      <div class="detailed_information" >
       <div class="info_table" >
         <el-descriptions  title="用户信息"  :column="1" size="medium">
         <el-descriptions-item label="账号">{{userInfo.account}}</el-descriptions-item>
         <el-descriptions-item label="用户名">{{userInfo.userName}}</el-descriptions-item>
         <el-descriptions-item label="所属组织">{{userInfo.providerName}}</el-descriptions-item>
         <el-descriptions-item  label="角色">
           <el-tag size="small">{{userInfo.roleName}}</el-tag>
           <el-checkbox disabled v-model="!!userInfo.isAdmin " style="margin-left: 10px">管理员</el-checkbox>
         </el-descriptions-item>
           <el-descriptions-item label="手机号">{{userInfo.phone}}</el-descriptions-item>
         <el-descriptions-item label="邮箱">
           {{userInfo.email}}
         </el-descriptions-item>
         <el-descriptions-item label="备注">
           <el-tag type="info" size="small">{{userInfo.remark||"未录入备注"}}</el-tag>
         </el-descriptions-item>
       </el-descriptions>
       </div>


      <div class="head_part">
        <div class="head_portrait"> <el-avatar   fit="cover" :size="200" :src="userInfo.avatar"></el-avatar> </div>

        <el-button class="replace_picture"
                   @click="isShowChangePhotoDialogVisible = true" icon="el-icon-camera">更换头像</el-button>
      </div>
    </div>
    <el-button round icon="el-icon-edit" class="edit_information" @click="openDialog" >编辑信息</el-button>
  </div>
</template>

<script>
import CommonForm from "@/components/common/CommonForm";
import {check_captcha, checkNewEmail, getCode, getUserInfo, saveChange} from "api/accountManage/userInfo";
import router from "@/router";
import {uploadImg} from "api/other/uploadImg"

export default {
  inject:['reload'],
  name: "userInfo",
  components: {CommonForm},
  created() {
    this.getInfo();
  },
  data() {

    const checkEmail = (rule, value, callback) => {
      //邮箱格式验证
      const pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (value === '') {
        //邮箱为空
        this.getCodeBtnDisable = true
        callback();
      }
      if (!pattern.test(value)) {
        //邮箱格式检查
        this.getCodeBtnDisable = true
        callback(new Error("邮箱格式错误！"));
      } else {
        //检查邮箱是否被注册
        checkNewEmail(value).then((res) => {
          const resCode = res.success;
          if (resCode) {
            this.getCodeBtnDisable = true
            callback(new Error("邮箱已被注册！"))
          } else {
            this.getCodeBtnDisable = false
            callback();
          }
        }).catch(onerror => {
          callback(new Error("网络问题，无法验证邮箱是否已注册"))
          this.getCodeBtnDisable = true
        })
      }
    }
    const checkCaptcha = (rule,value,callback) => {
      if (value === ''){
        callback(new Error("请输入验证码"))
      }else {
        const data = {
          email:this.newUserInfForm.newEmail,
          captcha:value,
          type:3
        }
        check_captcha(data).then((res)=>{
          if (res.success){
            callback();
          }
          else {
            callback(new Error("验证码错误"));
          }
        }).catch(()=>{
          callback(new Error("网络问题，无法验证"))
        })
      }
    }
    return {
      //用户信息
      userInfo: {
        account: "111",//账号
        userName: "Jay Chou",//用户名
        providerName: "寮步镇服务商",//组织名
        roleName: "管理员",//角色
        isAdmin: true,//管理员
        phone: "13111111111",//手机号
        email: "11111111@gmail.com",//邮箱
        remark: "hhhhh",//备注
        avatar: "https://joey_ma.gitee.io/head_portrait.jpg"//头像
      },
      //DiaLog
      fileList:[],
      isShowChangePhotoDialogVisible: false,
      isShowChangeEmailDialogVisible: false,
      isShowChangeInfDialogVisible:false,
      imageUrl:'',//保存的头像

      newUserInfForm: {
        userName: '',//用户名，String
        provider: '',//服务商ID，String
        oldEmail: '',//旧邮箱，String
        verificationCode: "",//验证码，String
        newEmail: "",//新邮箱，String
        remark: '',//备注，String
        },
      newUserInfFormLabel:[
        {
          model:'userName',
          label:'用户名',
          width: "70",
          placeholder:''
        },
        {
          model: "provider",
          label:'所属组织',
          width: "70",
          type:'cascaderArea',
          placeholder:''
        },
        {
          label: "旧邮箱",
          model: "oldEmail",
          width: "70",
          disable:true
        },
        {
          label: "新邮箱",
          model: "newEmail",
          width: "70",

        },
        {
          label: "验证码",
          model: "verificationCode",
          width: "50",
        },
        {
          model: 'remark',
          label:'备注',
          type:'textarea',
          width: "90"
        }
      ],
      newUserInfFormConfig:{
        labelWidth: "100px",
        rules: {
          newEmail: [
            {validator: checkEmail, trigger: 'blur'},

          ],
          verificationCode: [
            {validator:checkCaptcha, trigger: 'blur'}
          ]
        }
      },
        //验证码按钮等待
          getCodeBtnDisable:true,
        // savaHeadPortraitBtnDisable: false,
        // cancelHeadPortraitBtnDisable: false,
          buttonDisabled:false,
        timeCounter:"" //验证码获取限时30s/次
      }
    }
  ,
  methods: {
    //获取用户基本信息
    getInfo() {
      getUserInfo()
        .then((res) => {
          if (res.data.success) {
            const resData = res.data;
            this.userInfo = resData.data;
            //获取的旧邮箱和备注保存至更换信息的表单，oldEmail属性为disable
            this.newUserInfForm.oldEmail = resData.data.email;
            this.newUserInfForm.remark = resData.data.remark;
            this.newUserInfForm.userName = resData.data.userName;
            this.newUserInfForm.provider = resData.data.providerName
            return true;
          } else {
            this.$notify({
              type: 'error',
              message:res.data.message
            })
            return  router.push({
              path:'/login'
            })
          }
        }).catch((err) => {
        this.$message({
          showClose: true,
          type: 'error',
          message: '获取用户信息失败，请查看控制台'
        })
        return false;
      })
    },
    openDialog(){
      let newInf = this.newUserInfForm;
      newInf.oldEmail =  this.userInfo.email;
      newInf.provider = this.userInfo.providerName;
      this.newUserInfFormLabel[0].placeholder = this.userInfo.userName;
      this.newUserInfFormLabel[1].placeholder = this.userInfo.providerName;
      this.newUserInfFormLabel[5].placeholder = this.userInfo.remark;
      this.isShowChangeInfDialogVisible = true;
    },
    //提交用户修改信息
    saveUserInf(newInf){
      this.buttonDisabled = true
      saveChange(newInf).then(res =>{
        if (res.success){
          this.$notify({
            type:'success',
            message:'信息已保存'
          })
          this.buttonDisabled = false;
         return  this.reload();
        }else {
          this.buttonDisabled = false;
          return this.$notify({
            type:'success',
            message:res.message
          })
        }
      }).catch(onerror =>{
        console.log(onerror);
        this.buttonDisabled = false
        return this.$notify({
          type:'error',
          message:'请求失败，请查看控制台'
        })
      })
    },
    //获取验证码
    getCode() {

      //form-data参数数据
      const data = {
        email: this.userInfo.email,
        type: 3
      };
      getCode(data)
        .then((res) => {
          this.getCodeBtnDisable = true
          const resData = res.data;
          if (resData.code == 200) {
            // 30秒获取一次验证码
            this.timeCounter = 30;
            //1s累减
            let timer =  setInterval(
              ()=> {
                this.timeCounter --;
              },1000);
            //异步执行计时30s
            setTimeout(()=>{
              clearInterval(timer)
              this.timeCounter = "";
              this.getCodeBtnDisable = false;
            },30000)
            this.$message({
              center: true,
              type: 'success',
              message: '验证码已发送'
            })
          } else {
            //发送失败
            this.getCodeBtnDisable = false;
             this.$message({
              center: true,
              type: 'warning',
              message: resData.message
            })
          }

        })
        .catch((err) => {
         console.log(err);

        this.$message({
            center: true,
            type: 'error',
            message: "请求失败，请查看控制台"
          })
          this.getCodeBtnDisable = false;
        })
    },
    //上传图片
    uploadHeadPortrait(datas) {
      uploadImg(2,datas.file).then((res)=>{
        if (res.data.success){
          console.log(res);
         return  this.imageUrl = res.data.data;
        }
      })

    },
    //检查上传文件
    checkFile(file){
      const isImg = /(.jpg|.png)$/.test(file.name)
      const imgSize = (file.size / 1024 / 1024 < 2)
      if (!isImg){
        this.$message({
          message:'图片格式要求为jpg或者png格式',
          type:'warning'
        })
        this.fileList = []
        return  false
      }
      if (!imgSize){
        this.$message({
          message:'图片大小要求低于2M',
          type:'warning'
        })
        this.fileList = [];
        return  false
      }
       return isImg && imgSize ;
    },
    //提交头像
    submitAvatar(avatar){
      this.buttonDisabled = true;
      const data = {avatar:avatar}
      saveChange(data).then((res)=>{
        const result = res && parseInt(res.code,10)
        if (result === 200){
          this.userInfo.avatar = res.data.avatar;
          this.buttonDisabled = false;
          this.$message({
            center:true,
            message:"头像更换成功",
            type:'success'
          })
        }else {
          this.buttonDisabled = false;
          this.$message({
            center:true,
            message:res.message,
            type:'warning'
          })
        }
      }).catch(()=>{
        this.buttonDisabled = false;
        this.$message({
          center:true,
          message:"网络出错，请稍后重试",
          type:'error'
        })
      })
    }
  }
}

</script>

<style>
.el-dialog{
  margin-top: 15vh;
  width: 500px;
}

.detailed_information{
  /*overflow-x: hidden;*/
  min-width: 500px;
  max-width: 2000px;
  width: 80%;
  flex-direction: row;
  display: flex;
  justify-content: space-evenly;
  /*transform: translateX(20px);*/
}
.detailed_information div{
  flex: 1;
}
.detailed_information .info_table{
  position: relative;
  top: 20px;
  left: 40px;
}
.el-descriptions__body .el-descriptions__table .el-descriptions-item__cell{
  line-height: 2.5!important;
}
 .detailed_information .head_part{
   position: relative;
   left: 0;
   transform: translateX(50%);
  }
 .detailed_information .replace_picture {
   position: relative;
   top: 30px;
   left: 50px;
 }
.el-upload {
  width: auto;
  /*display:inline;*/
  /*display: flex;*/
  /*justify-content: center;*/
  /*align-items: center;*/
}

 .upload_part{
   width: 400px;
   height: 200px;
}
.el-upload {
  /*background: #409EFF;*/
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transform: translate(80%, 0%);
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 168px;
  line-height: 178px;
  text-align: center;
}

.edit_information{
  margin-top: 100px ;
  transform:translate(-50%,50%);
  position: relative;
  left: 50%;
  bottom:10px;
}
</style>
